package com.gitee.faster.webdav.kernel.protocol.filter;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.gitee.faster.webdav.common.constant.MethodEnum;
import com.gitee.faster.webdav.exception.WriteException;
import com.gitee.faster.webdav.kernel.protocol.HttpExchange;
import org.smartboot.http.common.utils.Mimetypes;

import java.io.IOException;
import java.io.InputStream;

/**
 * 处理首页静态资源
 *
 * @author hongda.li
 */
public class HttpFilterStaticResource implements HttpFilter {
    /**
     * 接受的请求后缀
     */
    private static final String[] ACCEPT_SUFFIX = {".html", ".css", ".ico", ".js"};

    /**
     * 静态资源类路径前缀
     */
    private static final String CLASS_PATH_PREFIX = "static";

    @Override
    public boolean doNext(HttpExchange httpExchange) {
        // 仅拦截GET请求
        if (MethodEnum.GET != httpExchange.getMethodEnum()) {
            return true;
        }

        // 仅拦截指定类型的静态资源
        if (!CharSequenceUtil.endWithAny(httpExchange.getPath(), ACCEPT_SUFFIX)) {
            return true;
        }

        // 资源名称
        String resourceName = CLASS_PATH_PREFIX + httpExchange.getPath();

        // 资源类型
        httpExchange.setContentType(Mimetypes.getInstance().getMimetype(resourceName));

        // 读取资源输入流并写入到HTTP输出流
        try (InputStream inputStream = ResourceUtil.getStreamSafe(resourceName)) {
            if (inputStream == null) {
                // 非内置系统静态资源可能是WebDav服务挂载目录中的资源
                return true;
            } else {
                inputStream.transferTo(httpExchange.getOutputStream());
            }
        } catch (IOException e) {
            throw new WriteException("写入静态资源异常", e);
        }

        return false;
    }
}
